//------------------------------------------------------------------------------

#include <stdlib.h>
#include <string.h>

#include "util.h"

//------------------------------------------------------------------------------
#define CR						'\r'
#define LF						'\n'
//------------------------------------------------------------------------------
int split(char *src, char ***dst) {
	int nbLigne = 0;
	char *oldPtr = src;
	char *ptr = src;
	int bufferSize = 0;
	char *buffer;

	if (src != 0 && strlen(src) != 0) {

		int i;
		int fini = 0;

		do {
			int sizeSegment;
			ptr = strchr(oldPtr, LF);
			if (ptr != 0) {
				sizeSegment = ptr - oldPtr;

				if (ptr != src && *(ptr - 1) == CR) {
					sizeSegment--;
				}
			} else {
				sizeSegment = strlen(oldPtr);
				fini = 1;
			}

			reallocEx(&buffer, bufferSize, sizeSegment + 1);

			strncpy(&buffer[bufferSize], oldPtr, sizeSegment);
			bufferSize += sizeSegment;
			buffer[bufferSize] = 0;
			bufferSize++;

			oldPtr = ptr + 1;
			nbLigne++;
		} while (!fini);

		*dst = (char **) malloc(nbLigne * sizeof(char *));
		ptr = buffer;
		for (i = 0; i < nbLigne; i++) {
			(*dst)[i] = ptr;
			ptr = ptr + strlen(ptr) + 1;
		}
	}

	return nbLigne;
}
//------------------------------------------------------------------------------

